<?php
session_start();
global $appLog;//全局log
define('ENV', 'DEV');

if(ENV=='DEV')
{
	
	define('URL', 'http://meimeidas.hz.taeapp.com/mmd/');
	define('DOMAIN', 'http://meimeidas.hz.taeapp.com/mmd/');
	define('AUTHURL', 'https://oauth.taobao.com/authorize?client_id=23067266&response_type=code&redirect_uri=http://mac-b.cs.com/?c=top_ctrl&m=test');
	// define('AUTHURL', 'https://oauth.taobao.com/authorize?client_id=23067266&response_type=code&redirect_uri=http://mac-b.cs.com/oauth.php');
	define('ADMINURL', 'http://meimeidas.hz.taeapp.com/mmd/tms/page/build.php');
	define('QNADMINURL', 'http://meimeidas.hz.taeapp.com/mmd/qntms/page/build.php');
	
	define('PREVWIEWURL', 'http://meimeida.ews.m.jaeapp.com/mmd/tms/preview.php');
	define('PAGEURL', 'http://meimeida.ews.m.jaeapp.com/mmd/tms/page.php');

	// require_once dirname(__FILE__).'/../phptae-sdk/tae.php';
	// $appLog = Alibaba::AppLog();
}
else
{
	//front end
	define('PREVWIEWURL', 'https://meimeida.ews.m.jaeapp.com/tms/preview.php');
	define('PAGEURL', 'http://meimeida.ews.m.jaeapp.com/tms/page.php');

	//backend
	define('URL', 'http://meimeidas.hz.taeapp.com');
	define('DOMAIN', 'http://meimeidas.hz.taeapp.com');
	define('AUTHURL', 'https://oauth.taobao.com/authorize?client_id=23067266&response_type=code&redirect_uri=http://meimeidas.hz.taeapp.com/tms/oauth.php');
	define('ADMINURL', 'http://meimeidas.hz.taeapp.com/tms/page/build.php');
	define('QNADMINURL', 'http://meimeidas.hz.taeapp.com/qntms/page/build.php');

	
	
	$appLog = Alibaba::AppLog();
}


date_default_timezone_set("Asia/Shanghai");


class Services_Utility{
		public $appkey = '23067266';
		public $appSecret = '0bfebee04873d852dda5c7ec2d938f2e';
		public $access_token = '';
		public $shopId;
		public $sellId;
		public $nick;
	
	//public $domain ='http://taobao.play.admin.jaeapp.com:8080/public/';

    /* ENV (online)
	
    public $url = 'http://match.play.admin.jaeapp.com';
    public $domain ='http://match.play.admin.jaeapp.com/';
	public $oauthUrl = 'https://oauth.taobao.com/authorize?client_id=23067266&response_type=code&redirect_uri=http://match.play.admin.jaeapp.com/oauth.php';
	public $adminUrl = 'http://match.play.admin.jaeapp.com/tms/page/build.php';
	public $qnAdminUrl = 'http://match.play.admin.jaeapp.com/qntms/page/build.php';
	public $previewUrl = 'http://match.play.m.jaeapp.com/tms/preview.php';
	public $pageUrl = 'http://match.play.m.jaeapp.com/tms/page.php';*/
	

    /*
    TEST ENV (online)
    */
    /*  
    public $url = 'http://match-1.play.admin.jaeapp.com';
	public $domain ='http://match-1.play.admin.jaeapp.com/';
	public $oauthUrl = 'https://oauth.taobao.com/authorize?client_id=23067266&response_type=code&redirect_uri=http://match-1.play.admin.jaeapp.com/oauth.php';
	public $adminUrl = 'http://match-1.play.admin.jaeapp.com/tms/page/build.php';
	public $qnAdminUrl = 'http://match-1.play.admin.jaeapp.com/qntms/page/build.php';
	public $previewUrl = 'http://match-1.play.m.jaeapp.com/tms/preview.php';
	public $pageUrl = 'http://match-1.play.m.jaeapp.com/tms/page.php';
  */

    /*
	TEST ENV (offline)
	*/
 
	public function __construct()
	{
		if(ENV != 'DEV')
		{

			/*
			$acs_session_conf = array(
		    'username'=>'3af1b25e89b111e4',
		    'password'=>'123_Jae_ASD',
		    'host'=>'3af1b25e89b111e4.m.jst.cnhzalicm10pub001jae001.ocs.aliyuncs.com',
		    'port'=>'11211',
		    'life_time' => 1800,
			);

			$acs_session_handler = Alibaba::Session($acs_session_conf['life_time']);
			if($acs_session_handler && $acs_session_handler->setSavePath($acs_session_conf))
			{
			session_set_save_handler(
			    array(
			        $acs_session_handler,
			        "open"
			    ), array(
			        $acs_session_handler,
			        "close"
			    ), array(
			        $acs_session_handler,
			        "read"
			    ), array(
			        $acs_session_handler,
			        "write"
			    ), array(
			        $acs_session_handler,
			        "destroy"
			    ), array(
			        $acs_session_handler,
			        "gc"
			    )
			);

			register_shutdown_function('session_write_close');
			}

			*/

		}

	}

	public $url = URL;
	public $domain = DOMAIN;
	public $oauthUrl = AUTHURL;
	public $adminUrl = ADMINURL;
	public $qnAdminUrl = QNADMINURL;
	public $previewUrl = PREVWIEWURL;
	public $pageUrl = PAGEURL;

	/*
	* @desc taobao oauth Login
	* @param $params["token"] 
	* @param $params["code"]
	* @param $params["redirectUrl"]
	*/
	
	public function oauth()
	{	
		
		if((@$_GET['error'] == 'access_denied') && (@$_GET['error_description'] == 'parent account forbid this sub account to access app.')){
			echo('子账号未授权！请联系主账号授予应用访问权限！');die;
		}
		$code = @$_GET["code"];
		$refer = @$_GET["refer"];
		$grant_type = 'authorization_code';
		$redirect_uri = $this->url.'/oauth.php';
		$client_id = $this->appkey;
		$client_secret = $this->appSecret;
		$postfields= array('grant_type'=> $grant_type,
    	'client_id'     => $client_id,
    	'client_secret' => $client_secret,
    	'code'          => $code,
    	'redirect_uri'  => $redirect_uri
		);
		$url = 'https://oauth.taobao.com/token';
		$tokenstr = $this->curl($url,$postfields);
		$tokenarr =json_decode($tokenstr,true);	

		$token = $tokenarr["access_token"];
		$user['user_id'] = $tokenarr["taobao_user_id"];
		$user['nick'] = urldecode($tokenarr['taobao_user_nick']);
		$_SESSION['sellid'] = $tokenarr["taobao_user_id"];
		$_SESSION['access_token'] = $token;
		$this->access_token = $token;
		$this->nick = $user['nick'];
		/*
		sub nick
		*/
		$_SESSION['subNick'] = urldecode($tokenarr['sub_taobao_user_nick']);
	
		/*
		get shop id
		*/
		$parameters['visitor_nick'] = $user['nick'];
		$result = $this->getSeller($parameters);

		if($result)
		{
			$this->createPicDir();
			if($refer)
			{
				$redirect_uri = $refer;
			}
			else
			{
				$redirect_uri = $this->url.'/tms/page/index.php';
			}
			header("Location: $redirect_uri");
		}
	}

	/*
	 * 退出登录
	 */
	public function logoff(){
		unset($_SESSION['shopid']);
		unset($_SESSION['sellid']);
		unset($_SESSION['nick']);
		unset($_SESSION['subNick']);
		unset($_SESSION['access_token']);
	}
	/*
	get nick
	*/
	function getSellerDetails()
	{
		$details = array();
		$details['shopId'] = $_SESSION['shopid'];
		$details['userId'] = $_SESSION['sellid'];
		$details['nick'] = $_SESSION['nick'];
		$details['subNick'] = $_SESSION['subNick'];
		$details['accessToken'] = $_SESSION['access_token'];

		//TODO TEST
		/*
		$_SESSION['shopid'] = '60024831';
		$_SESSION['userId'] = '21451241';
		$_SESSION['nick'] = 'liangjiaoxj';
		$_SESSION['access_token'] = '6201414369e316b9113563ZZa6a97f1fc2fe62eb83fabf921451241';
		

		$details['shopId'] = '60024831';
		$details['userId'] = '21451241';
		$details['nick'] = 'liangjiaoxj';
		$details['subNick'] = '';
		$details['accessToken'] = '6201414369e316b9113563ZZa6a97f1fc2fe62eb83fabf921451241';
		*/
		return $details;
	}
	/*
     * 判断登录状态
     */
	public function checkLogin(){
		$shopDetails = $this->getSellerDetails();
		$shopId = $shopDetails['shopId'];
		$sellId = $shopDetails['userId'];
		$nick = $shopDetails['nick'];
		if(empty($shopId) || empty($sellId) || empty($nick))
		{
			$result['success'] = false;
			$result['code'] = 26;
			$result['msg'] = '授权失败';
			//$appLog->warn('shopid:'.$shopId.' step:授权失败 '.$result['msg']);
			echo (json_encode($result));
			die();
		}
		$this->shopId = $shopId;
		$this->sellId = $sellId;
		$this->nick = $nick;
	}

	/*
	* @desc curl
	*/
	function curl($url, $postFields = null)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		//curl_setopt($ch, CURLOPT_FAILONERROR, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


			$postBodyString = "";
			foreach ($postFields as $k => $v)
			{
				$postBodyString .= "$k=" . urlencode($v) . "&";
			}
			unset($k, $v);
			curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1));

		$reponse = curl_exec($ch);

		curl_close($ch);
		return $reponse;
	}


	/*
	@desc  get seller
	*/
	public function getSeller($parameters)
	{

		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('taobao.shop.get');
		$tbsb->set('fields',"sid,cid,title,nick,desc,bulletin,pic_path,created,modified");
		$tbsb->set('nick',$parameters['visitor_nick']);
		$resp = $tbsb->get();
		/*
		$result
		*/

		if($resp['shop_get_response'])
		{
			$_SESSION['shopid'] = $resp['shop_get_response']['shop']['sid'];
			$_SESSION['nick'] =  $resp['shop_get_response']['shop']['nick'];
			return true;

		}
		else
		{
			echo $resp['sub_msg'];
            return false;
		}

	}

	/*
	@desc  获取店铺详情
	*/
	public function getShopInfo($parameters)
	{
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('taobao.shop.get');
		$tbsb->set('fields',"sid,cid,title,nick,desc,bulletin,pic_path,created,modified");
		$tbsb->set('nick',$parameters['nick']);
		$resp = $tbsb->get();
		return $resp;
	}


	/*
	* @desc get product list
	* @param string $params['nick']
	*/
	public function getCategoryList($params)
	{

		$c = new TopClient;
		$c->appkey = $this->appkey;
		$c->secretKey = $this->appSecret;
		$req = new SellercatsListGetRequest();
		$req->setNick($params['nick']);
		$resp = $c->execute($req);
		$resp =  json_encode($resp);
		$resp = json_decode($resp,true);
		return $resp;
	}



	/*
	 * 根据nuiid获取商品信息
	 */
	public function getItemSeller($params){
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('taobao.item.seller.get');
		$tbsb->set('fields',"num_iid,price,title,nick,approve_status,cid,num,list_time,modified,is_virtual,outer_id,pic_url,item_img,sold_quantity");
		$tbsb->set('num_iid',$params['num_iid']);
		$resp = $tbsb->get();
		return $resp ;
	}


	/*
	 * 根据out_id获取商品信息
	 */
	 public function getCustomItems($params){
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('taobao.items.custom.get');
		$tbsb->set('fields',"num_iid,price,title,nick,approve_status,cid,num,list_time,modified,is_virtual,outer_id,pic_url,sold_quantity");
		$tbsb->set('outer_id',$params['out_id']);
		$resp = $tbsb->get();
		$resp = json_encode($resp);
		$resp = json_decode($resp,true);
		return $resp ;
	 }

	 /*
	 * 批量获取商品详细信息
	 */
	 public function getItemsList($params){
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('taobao.items.seller.list.get');
		$tbsb->set('fields',"num_iid,price,title,nick,approve_status,cid,num,list_time,modified,is_virtual,outer_id,pic_url,sold_quantity");
		$tbsb->set('num_iids',$params['num_iids']);
		$resp = $tbsb->get();
		return $resp ;
	 }

	/*
	 * 淘宝卖家搭配套餐查询
	 */
	public function queryMeal($params){
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('taobao.promotion.meal.get');
		if($params['mealid']){
			$tbsb->set('meal_id',$params['mealid']);
		}
		$tbsb->set('status','VALID');
		$resp = $tbsb->get();
		return $resp ;
	}

	/*
	 * alibaba卖家搭配套餐查询
	 */
	public function alibabaQueryMeal(){
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('alibaba.interact.ump.meal.query');
		$resp = $tbsb->get();
		return $resp ;
	}
	/*
	* 天猫搭配宝查询
	* @params['itemid']
	*/
	public function combQuery($params)
	{
		$tbsb = new Services_Tbsb();
		$tbsb->query('tmall.promotion.comb.query');
		$tbsb->set('item_id',$params['itemid']);
		$resp = $tbsb->get();

		$combResp['fixed'] = $resp['tmall_promotion_comb_query_response']['data']['fixed_combs']['fixed_comb'];
		$combResp['free'] = $resp['tmall_promotion_comb_query_response']['data']['free_combs']['free_comb'];
		$result = array();
		foreach($combResp['fixed'] as $k=>$v)
		{
			$result[$v['comb_id']] = array('mealId'=>$v['comb_id'],'mealName'=>$v['title'],'');

		}

		$result = array();
		//$result['mealId'] =
		//$combResult =

	}

	/*
	 * 卖家优惠券列表查询
	 */
	public function getCoupons($params){
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('taobao.promotion.coupons.get');
		$tbsb->set('page_no',$params['page_no']);
		$tbsb->set('page_size',$params['page_size']);
		$resp = $tbsb->get();
		return $resp ;
	}

	/*
	 * 卖家优惠券领取活动查询
	 */
	public function getPromtionActivity($params){
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('taobao.promotion.activity.get');
		if($params['activity_id']){
			$tbsb->set('activity_id',$params['activity_id']);
		}
		$resp = $tbsb->get();
		return $resp ;
	}

	/*
	* @desc get products list
	* @param string $params['q']
	* @param string $params['pageNo']
	* @param string $params['pageSize']
	* @param string $params['accessToken']
	* @param string $params['orderBy'] //list_time:desc
		默认:list_time:desc
		最后修改:modified:desc
		最新上架:list_time:desc
		库存:num:desc
		销量:sold_quantity:desc
	list_time(上架时间),delist_time(下架时间),num(商品数量)，modified(最近修改时间)，sold_quantity（商品销量）
	*/
	public function getProductLists($params)
	{

		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('taobao.items.onsale.get');
		$tbsb->set('fields',"num_iid,price,title,nick,approve_status,cid,num,list_time,modified,is_virtual,outer_id,pic_url,sold_quantity");
		$tbsb->set('q',$params['q']);
		$tbsb->set('seller_cids',$params['cids']);
		$tbsb->set('order_by',$params['orderBy']);
		$tbsb->set('page_no',$params['pageNo']);
		$tbsb->set('page_size',$params['pageSize']);
		$resp = $tbsb->get();
		$resp = json_encode($resp);
		$resp = json_decode($resp,true);
		return $resp ;
	}

	/*
	*商品优惠详情查询
	*/
	public function getPromotion($params)
	{
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('taobao.ump.promotion.get');
		$tbsb->set('item_id',$params['item_id']);
		$resp = $tbsb->get();
		$resp = json_encode($resp);
		$resp = json_decode($resp,true);
		return $resp ;
	}
	/*
	*商品折扣信息查询 token from cache
	*/
	public function getDiscountPrice($params)
	{
		$token = $this->getCache('shop_token_'.$params['shopId']);
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($token);
		$tbsb->query('taobao.ump.promotion.get');
		$tbsb->set('item_id',$params['item_id']);
		$resp = $tbsb->get();
		$resp = json_encode($resp);
		$resp = json_decode($resp,true);
		return $resp ;
		
	}
	/*
	*商品信息查询 token from cache
	*/
	public function getItemTokenFromCache($params)
	{
		$token = $this->getCache('shop_token_'.$params['shopId']);
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($token);
		$tbsb->query('taobao.item.seller.get');
		$tbsb->set('fields',"num_iid,price,title,nick,approve_status,cid,num,list_time,modified,is_virtual,outer_id,pic_url,item_img,sold_quantity");
		$tbsb->set('num_iid',$params['num_iid']);
		$resp = $tbsb->get();
		return $resp ;
		
	}
	

	/*
	*获取库存
	*/
	public function getInventory($params)
	{
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('taobao.items.inventory.get');
		$tbsb->set('fields',"num_iid,price,title,nick,approve_status,cid,num,list_time,modified,is_virtual,outer_id,pic_url,sold_quantity");
		$tbsb->set('q',$params['q']);
		$tbsb->set('cid',$params['cids']);
		$tbsb->set('order_by',$params['orderBy']);
		$tbsb->set('page_no',$params['pageNo']);
		$tbsb->set('page_size',$params['pageSize']);
		$resp = $tbsb->get();
		$resp = json_encode($resp);
		$resp = json_decode($resp,true);
		return $resp ;
	}

	/*
	*获取前台展示的店铺内卖家自定义商品类目
	*/
	public function getSellercatsList()
	{
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('taobao.sellercats.list.get');
		$tbsb->set('nick',$_SESSION['nick']);
		$resp = $tbsb->get();
		return $resp ;
	}


		/*
	get dead line
	@$params['nick'] 淘宝会员名 
	@$params['article_code']商品编码，从合作伙伴后台（my.open.taobao.com）-收费管理-收费项目列表 能够获得该应用的商品代码 
	*/
	public function getDeadLine($params)
	{
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('taobao.vas.subscribe.get');
		$tbsb->set('nick',$params['nick']);
		$tbsb->set('article_code',$params['article_code']);
		$resp = $tbsb->get();
		return $resp ;
		
	}
	
	/*
	@desc 获取图片分类信息
	*
	*/
	public function getPictureCategory($param)
	{
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);

		$tbsb->query('taobao.picture.category.get');
		if($param['cateName']){
			$tbsb->set('picture_category_name',$param['cateName']);
		}
		if($param['pid']){
			$tbsb->set('parent_id',$param['pid']);
		}
		if($param['cid']){
			$tbsb->set('picture_category_id',$param['cid']);
		}
		$tbsb->set('type','user-define');
		if($_SESSION['shopid']=='64661419')
		{
			$tbsb->set('modified_time','2016-01-01 00:00:00');
		}
		$resp = $tbsb->get();
		return $resp;
	}

	public function testImgTree($param)
	{
		$tbsb = new Services_Tbsb();
		$tbsb->setSession('6200602d2fhj322650e96c85ab6873f1a4863774f22d42d2646126384');
		
		$tbsb->query('taobao.picture.category.get');
		if($param['cateName']){
			$tbsb->set('picture_category_name',$param['cateName']);
		}
		
		if($param['cid']){
			$tbsb->set('picture_category_id',$param['cid']);
		}
	
		$tbsb->set('type','user-define');
		$tbsb->set('modified_time','2015-01-01 00:00:00');
		$resp = $tbsb->get();
		return $resp;
	}
	

	/*
	@desc 获取图片信息
	@param array $param
	*/
	public function getPictureInfo($param)
	{
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('taobao.picture.get');
		if($param['cid']){
			$tbsb->set('picture_category_id',$param['cid']);
		}
		if($param['id']){
			$tbsb->set('picture_id',$param['id']);
		}
		if($param['title']){
			$tbsb->set('title',$param['title']);
		}
		if($param['order_by']){
			$tbsb->set('order_by',$param['order_by']);
		}
		if($param['start_date']){
			$tbsb->set('start_date',$param['start_date']);
		}
		if($param['end_date']){
			$tbsb->set('end_date',$param['end_date']);
		}
		if($param['page_no']){
			$tbsb->set('page_no',$param['page_no']);
		}
		if($param['page_size']){
			$tbsb->set('page_size',$param['page_size']);
		}
		if($param['modified_time']){
			$tbsb->set('modified_time',$param['modified_time']);
		}
		if($param['urls']){
			$tbsb->set('urls',$param['urls']);
		}
		$resp = $tbsb->get();
		$resp = json_encode($resp);
		$resp = json_decode($resp,true);
		return $resp ;
	}


	/*
	@desc 上传图片
	@param array $param
	*/
	public function uploadPicture($param){
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('taobao.picture.upload');
		$tbsb->set('picture_category_id',$param['cid']);
		$tbsb->set('img',$param['img']);
		$tbsb->set('image_input_title',$param['inputtitle']);
		$resp = $tbsb->get();
		return $resp ;
	}


	/*
	@desc 新增图片分类
	@param array $param
	*/
	public function createCategory($param){
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('taobao.picture.category.add');
		$tbsb->set('picture_category_name',$param['title']);
		$tbsb->set('parent_id',$param['parent_id']);
		$resp = $tbsb->get();
		$resp = json_encode($resp);
		$resp = json_decode($resp,true);
		return $resp ;
	}


	/*
	 * fetch
	*/
	public function fetchItem($itemid)
	{
		$itemId = $itemid;
		$url = 'http://hws.m.taobao.com/cache/wdetail/5.0/?id='.$itemId.'&ttid=2013@taobao_h5_1.0.0&exParams={}';
		$result = $this->disguise_curl($url);
		$res = json_decode($result,true);
	
		$res_arr = json_decode($res['data']['apiStack'][0]['value'],true);
		$price = $res_arr['data']['itemInfoModel']['priceUnits'][(int)count($res_arr['data']['itemInfoModel']['priceUnits'])-1]['price'];
		$discountprice = $res_arr['data']['itemInfoModel']['priceUnits'][0]['price'];
		$sellcount = $res_arr['data']['itemInfoModel']['totalSoldQuantity'];
		$stock = $res_arr['data']['itemInfoModel']['quantity'];
		/*
		add item info
		*/
		$itemInfo = $res['data']['itemInfoModel'];
		$json = array('itemid'=>$itemInfo['itemId'],'title'=>$itemInfo['title'],'img'=>$itemInfo['picsPath'][0],'price'=>$price,'discountprice'=>$discountprice,'sellcount'=>$sellcount,'stock'=>$stock);
		return $json;
	}

	/*
	fetch item 6
	*/
	public function fetchItem6($itemid)
	{
		
		$itemId = $itemid;
		$url = 'http://api.m.taobao.com/gw/mtop.taobao.detail.getdetail/6.0?data='.urlencode('{"exParams":"{\"ttid\":\"2323@taobao_iphone_6.2.2\"}","itemNumId":"'.$itemid.'"}');
		$result = $this->disguise_curl($url);
		$result = urlencode($result);
		$result = urldecode($result);
		$result = json_decode($result,true);
		return $result;
		
	}

	/**
	* curl远程的图片或者html文件
	*
	*
	* @access public
	* @param string $url
	* @return string cotent
	*/

	public function disguise_curl($url, $proxy=null)
    {
        $curl = curl_init();

        // Setup headers - I used the same headers from Firefox version 2.0.0.6
        // below was split up because php.net said the line was too long. :/
        $header = array();
        $header[0]  = "Accept: text/xml,application/xml,application/xhtml+xml,";
        $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
        $header[] = "Cache-Control: max-age=0";
        $header[] = "Connection: keep-alive";
        $header[] = "Keep-Alive: 300";
        $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
        $header[] = "Accept-Language: en-us,en;q=0.5";
        $header[] = "Cookie: cna=l+pgC/cDdWcCAWVF+/5q+UVs; miid=3317872020099775032; __utma=6906807.434603219.1390489590.1390489590.1390489590.1; __utmz=6906807.1390489590.1.1.utmcsr=fuwu.taobao.com|utmccn=(referral)|utmcmd=referral|utmcct=/ser/detail.htm; x=e%3D1%26p%3D*%26s%3D0%26c%3D0%26f%3D0%26g%3D0%26t%3D0%26__ll%3D-1%26_ato%3D0; lzstat_uv=24182050841715729711|2581762@3201199@2945730@2948565@2798379@2043323@3045821@2805963@2738597@878758@2208862@3027305@3284827@2581759@2581747@2938535@2938538@2879138@3010391; ali_ab=60.186.203.48.1390489531936.4; l=asd890241::1397182032328::11; v=0; uc3=nk2=AmJam4TqFyWJ&id2=W8ncTY3m5dw%3D&vt3=F8dATHtpuP76kDFmmBg%3D&lg2=V32FPkk%2Fw0dUvg%3D%3D; existShop=MTM5NzYxMTM1NA%3D%3D; lgc=asd890241; tracknick=asd890241; sg=10d; cookie2=6b8940c7741e940084cc149db11f8b7c; mt=cp=0&np=&ci=1_1&cyk=0_0; cookie1=B0EwsR%2FpnjjSjqpUTsxO8woKrOXzJMXtv9vP4SUJA5I%3D; unb=80893640; t=43525df761cffb84c1297592f666dd75; publishItemObj=Ng%3D%3D; _cc_=UIHiLt3xSw%3D%3D; tg=0; _l_g_=Ug%3D%3D; _nk_=asd890241; cookie17=W8ncTY3m5dw%3D; pnm_cku822=117fCJmZk4PGRVHHxtNZngkZ3k%2BaC52PmgTKQ%3D%3D%7CfyJ6Zyd9OGcmY3YkZHYibx4%3D%7CfiB4D15%2BZH9geTp%2FJyN8PDJtLBMbCF4lHw%3D%3D%7CeSRiYjNhIHA3dWI0c2A4eGwmfz16PnhrNHJlMH1kJnc8bS1hfzoT%7CeCVoaEATTRBWFx1IEBRReHZYZg%3D%3D%7CeyR8C0obRRhYABdDABNTFAFGEU8XUxMFTgMVSREMSxxeG1MWCTMa%7CeiJmeiV2KHMvangudmM6eXk%2BAA%3D%3D; _tb_token_=3ee5e3b8e7690; uc1=lltime=1397569800&cookie14=UoLVYuvN1ebuMw%3D%3D&existShop=true&cookie16=Vq8l%2BKCLySLZMFWHxqs8fwqnEw%3D%3D&cym=1&cookie21=URm48syIZJTgtchfymSXVA%3D%3D&tag=3&cookie15=VFC%2FuZ9ayeYq2g%3D%3D";
        $header[] = "Pragma: "; // browsers keep this blank.

        if (!is_null($proxy)) {
            curl_setopt ($curl, CURLOPT_PROXY, $proxy);
        }

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4');
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_REFERER, 'http://m.taobao.com');
        curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
        curl_setopt($curl, CURLOPT_AUTOREFERER, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT,1);
        $html = curl_exec($curl); // execute the curl command
        curl_close($curl); // close the connection

        return $html; // and finally, return $html
    }

	/*
	load resource from asserts
	*/
	public function loadResource($filename)
	{
		$content = file_get_contents($filename, true);
		return json_decode($content,true);
		//$content  =urlencode($content);
		//if($content)
		//{
		//	return json_decode(urldecode($content),true);

		//}
		//else
		//{
		//	$appLog->error($content);
		//	return false;

		//}

	}


	/*
	@desc 图片裁剪
	@param array $param('path','x','y','w','h')
	*/
	public function imageCut($path, $x, $y, $w, $h)
	{
		$source_info   = getimagesize($path);
		$source_mime   = $source_info['mime'];
		switch ($source_mime)
		{
			case 'image/gif':
				$source_image = imagecreatefromgif($path);

				break;

			case 'image/jpeg':
				$source_image = imagecreatefromjpeg($path);
				break;

			case 'image/png':
				$source_image = imagecreatefrompng($path);
				break;

			case 'image/bmp':
				$source_image = imagecreatefrompng($path);
				break;

			default:
				return false;
				break;
		}
		$target_image  = imagecreatetruecolor($w, $h);
		imagecopy($target_image, $source_image, 0, 0, $x, $y, $w, $h);
		imagedestroy($source_image);
		return($target_image);
	}

	/*
	 *将图片空间目录递归展示
	 */
	public function getCategory($array,$pid=0){
		$arr=array();
		foreach($array as $k=>$v){
			if($v['parent_id']==$pid){
				$str = trim($v['picture_category_name']);
				$str = mb_ereg_replace('^(　| )+', '', $str);
				$str = mb_ereg_replace('(　| )+$', '', $str);
				$list['id'] = (string)$v['picture_category_id'];
				$list['value'] = $str;
				$list['parent'] = $v['parent_id'];
				$list['isleaf'] = true;
				if($this->getCategory($array,$v['picture_category_id'])){
					$list['children']=$this->getCategory($array,$v['picture_category_id']);
					$list['isleaf'] = false;
				}
				$arr[]=$list;
			}
		}
		return $arr;
	}

	/*
	 *将商品分类目录递归展示
	 */
	public function getItemsCategory($array,$pid=0){
		$arr=array();
		foreach($array as $k=>$v){
			if($v['parent_cid']==$pid){
				$list['cid'] = $v['cid'];
				$list['name'] = $v['name'];
				$list['parent'] = $v['parent_cid'];
				$list['isleaf'] = true;
				if($this->getItemsCategory($array,$v['cid'])){
					$list['children']=$this->getItemsCategory($array,$v['cid']);
					$list['name'] = ' '.$v['name'];
					$list['isleaf'] = false;
				}
				$arr[]=$list;
			}
		}
		return $arr;
	}

	/*
	 *去掉字符串的换行
	 */
	public function replaceString($string){
		$string = trim($string);
		$string = str_replace("\t","",$string);
		$string = str_replace("\r\n","",$string);
		$string = str_replace("\n","",$string);
		return $string;
	}

	/*
	 *获取文件内容
	 */
	public function getFileContents($path){
		$content = file_get_contents($path, true);
		return $content;
		//$content  =urlencode($content);
		//return urldecode($content);
	}






	/*
	 * 二维数组排序
	 */
	public function array_sort($arr,$keys,$type='asc'){
		$keysvalue = $new_array = array();
		foreach ($arr as $k=>$v){
			$keysvalue[$k] = $v[$keys];
		}
		if($type == 'asc'){
			asort($keysvalue);
		}else{
			arsort($keysvalue);
		}
		reset($keysvalue);
		foreach ($keysvalue as $k=>$v){
			$new_array[] = $arr[$k];
		}
		return $new_array;
	}

	/*
	set cache
	*/
	public function setCache($key,$value,$expired=2592000)//30天
	{
		if(ENV=='DEV')
		{
			$cache = new Memcache;
			$cache->connect('localhost', 11211) or die ("Could not connect");
			$result = $cache->set($key, $value, 0,$expired);
			return $result;

		}
		else
		{
			$config = array(
			'host'  => '3af1b25e89b111e4.m.jst.cnhzalicm10pub001jae001.ocs.aliyuncs.com',
			'port'  => '11211',
			'username' => '3af1b25e89b111e4',
			'password' => '123_Jae_ASD',
			'endpoint' => '', # 对于青岛机房的 ocs 实例时可以配置, 其它类型 ocs 可以不配置, 忽略此项
			);
			$cache = Alibaba::cache($config);
			$result = $cache->set($key, $value,$expired);
			return $result;

		}

	}
	/*
	get cache
	*/
	public function getCache($key)
	{

		if(ENV=='DEV')
		{
			$cache = new Memcache;
			$cache->connect('localhost', 11211) or die ("Could not connect");
			$result = $cache->get($key);
			return $result;
		}
		else
		{
			$config = array(
			'host'  => '3af1b25e89b111e4.m.jst.cnhzalicm10pub001jae001.ocs.aliyuncs.com',
			'port'  => '11211',
			'username' => '3af1b25e89b111e4',
			'password' => '123_Jae_ASD',
			'endpoint' => '', # 对于青岛机房的 ocs 实例时可以配置, 其它类型 ocs 可以不配置, 忽略此项
			);
			$cache = Alibaba::cache($config);

			$result = $cache->get($key);
			return $result;
		}
		

	}
	/*
	del cache
	*/
	public function delCache($key)
	{
		if(ENV=='DEV')
		{
			$cache = new Memcache;
			$cache->connect('localhost', 11211) or die ("Could not connect");
			$result = $cache->delete($key);
			return $result;
		}
		else
		{
			$config = array(
			'host'  => '3af1b25e89b111e4.m.jst.cnhzalicm10pub001jae001.ocs.aliyuncs.com',
			'port'  => '11211',
			'username' => '3af1b25e89b111e4',
			'password' => '123_Jae_ASD',
			'endpoint' => '', # 对于青岛机房的 ocs 实例时可以配置, 其它类型 ocs 可以不配置, 忽略此项
			);
			$cache = Alibaba::cache($config);
			$result = $cache->delete($key);
			return $result;
		}
		
	}

	/*
	 * 判断数组是否有空值
	 */
	public function isNullInArray($array){
		foreach($array as $k => $v){
			if(empty($v)){
				return false;
			}
		}
		return true;
	}

	/*
	 * 热区图片切割
	 */
	public function cutHotareaImg($string){
		include_once(dirname(__FILE__).'/simplehtmldom.php');
		$html = str_get_html(".".$string.".");
		foreach($html->find('div[class=cms-hot-area-content]') as $div){
			$picSrc = $div->find('img[class=cms-hot-area-img]',0)->src;
			$imgCode = $div->find('img[class=cms-hot-area-img]',0)->outertext;
			//创建图片操作对象
			$image = new Services_Image();
			for($i=0;$i<5;$i++){
				$randNum .= rand(0,9);
			}
			$imgName = time() . $randNum;
			$imgType = strtolower(substr(strrchr($picSrc,'.'),1));
			$title = $imgName . '.' . $imgType;
			$filePath = '../upload/' . $title;//图片存储在本地的路径
			try{
				$image->saveRemoteImage($picSrc,$filePath);//将图片空间的图片存到本地
			}catch(Exception $e){
				$appLog->warn($e);
				return $string;
			}


			if(file_exists($filePath)){
				$source_info = getimagesize($filePath);
				if(!$source_info){
					unlink($filePath);
					//$appLog->warn('image file error');
					return $string;

				}

				$imgWidth = $source_info[0];
				$imgHeight = $source_info[1];
				if(!$imgHeight || !$imgWidth){
					unlink($filePath);
					//$appLog->warn('image file error');
					return $string;
				}

				

				if($imgHeight <= $imgWidth){
					return $string;
				}
				/*if($imgWidth > 750){
					$image->resizeImage($filePath, $filePath ,750);//压缩
					$imgHeight = $imgHeight/($imgWidth/750);
					$imgWidth = 750;
				}*/
				$imgCount = ceil($imgHeight/$imgWidth);
				$source_mime   = $source_info['mime'];
				switch ($source_mime)
				{
					case 'image/gif':
						$source_image = imagecreatefromgif($filePath);
						break;

					case 'image/jpeg':
						$source_image = imagecreatefromjpeg($filePath);
						break;

					case 'image/png':
						$source_image = imagecreatefrompng($filePath);
						break;

					case 'image/bmp':
						$source_image = imagecreatefrompng($filePath);
						break;

					default:
						unlink($filePath);
						return $string;
				}
				$target_image = array();
				$y = 0;
				$cutImgPathArr = array();

				try{
					//切割图片
					for($i=0;$i<$imgCount;$i++){
						if($i == $imgCount-1){
							$target_image= imagecreatetruecolor($imgWidth, ($imgHeight%$imgWidth ? $imgHeight%$imgWidth :$imgHeight));
							imagecopy($target_image, $source_image, 0, 0, 0, $y, $imgWidth, ($imgHeight%$imgWidth ? $imgHeight%$imgWidth :$imgHeight));
						}else{
							$target_image= imagecreatetruecolor($imgWidth, $imgWidth);
							imagecopy($target_image, $source_image, 0, 0, 0, $y, $imgWidth, $imgWidth);
						}
						$newFile_cut = '../upload/' . 'cut_' .  $imgName . $i.'.' . $imgType;
						$cutImgPathArr[$i] = $newFile_cut;
						imagejpeg($target_image,$newFile_cut,100);
						imagedestroy($target_image);
						$y += $imgWidth;
					}
					unlink($filePath);
					imagedestroy($source_image);
				}catch(Exception $e){
					unlink($filePath);
					imagedestroy($source_image);
					$image->deletePics($cutImgPathArr);
					$appLog->warn($e);
					return $string;
				}
				$cid = $this->getUploadDir();
				$newHtml = '';
				foreach($cutImgPathArr as $k => $v){
					$param = array(
						'cid' => $cid ? $cid : 0,
						'img' => '@'.dirname(__FILE__).'/'.$v,
						'inputtitle' => time().$k
					);
					try{
						$res =$this->uploadPicture($param);//将裁剪好的图片上传到图片空间
					}catch(Exception $e){
						//$appLog->warn($e);
						$image->deletePics($cutImgPathArr);
						return $string;
					}
					if($res['error_response']){
						
						$appLog->warn(json_encode($res['error_response']));
						return $string;
					}else{
						$newCutImgPathArr[$k] = $res['picture_upload_response']['picture']['picture_path'];
						$newHtml .= '<img class="cms-hot-area-img img-lazyload" src="https://img.alicdn.com/imgextra/i3/21451241/TB2ganSiVXXXXbpXpXXXXXXXXXX-21451241.png" data-src="'.$res['picture_upload_response']['picture']['picture_path'].'_640x640q75.jpg_.webp">';
					}
				}

				if(!empty($newHtml)){
					$replaceString = str_replace($imgCode,$newHtml,$string);
				}else{
					$replaceString = $string;
					//$appLog->warn('error');
				}
				$image->deletePics($cutImgPathArr);
				return $replaceString;
			}else{
				unlink($filePath);
				$image->deletePics('not found file');
				return $string;
			}

		}
	}


	/*
	 * 动画模块切割(页面速度提升)
	 */
	public function cutAnimateImg($string)
	{

		include_once(dirname(__FILE__).'/simplehtmldom.php');
		$html = str_get_html(".".$string.".");
		foreach($html->find('div[class=cms-animateArea]') as $div){
			$picSrc = $div->find('img[class=cms-animateAreaBg]',0)->src;
			$imgCode = $div->find('img[class=cms-animateAreaBg]',0)->outertext;
			//创建图片操作对象
			$image = new Services_Image();
			for($i=0;$i<5;$i++){
				$randNum .= rand(0,9);
			}
			$imgName = time() . $randNum;
			$imgType = strtolower(substr(strrchr($picSrc,'.'),1));
			$title = $imgName . '.' . $imgType;
			$filePath = '../upload/' . $title;//图片存储在本地的路径
			try{
				$image->saveRemoteImage($picSrc,$filePath);//将图片空间的图片存到本地
			}catch(Exception $e){
				$appLog->warn($e);

				return $string;
			}
			
			if(file_exists($filePath)){

				$source_info = getimagesize($filePath);
			
				if(!$source_info){
					unlink($filePath);
	
					return $string;

				}

				$imgWidth = $source_info[0];
				$imgHeight = $source_info[1];
				if(!$imgHeight || !$imgWidth){
					unlink($filePath);
					//$appLog->warn('image file error');
					return $string;
				}

				

				if($imgHeight <= $imgWidth){
					return $string;
				}

				/*if($imgWidth > 750){
					$image->resizeImage($filePath, $filePath ,750);//压缩
					$imgHeight = $imgHeight/($imgWidth/750);
					$imgWidth = 750;
				}*/
				$imgCount = ceil($imgHeight/$imgWidth);
				$source_mime   = $source_info['mime'];
				switch ($source_mime)
				{
					case 'image/gif':
						$source_image = imagecreatefromgif($filePath);
						break;

					case 'image/jpeg':
						$source_image = imagecreatefromjpeg($filePath);
						break;

					case 'image/png':
						$source_image = imagecreatefrompng($filePath);
						break;

					case 'image/bmp':
						$source_image = imagecreatefrompng($filePath);
						break;

					default:
						unlink($filePath);
						return $string;
				}
				$target_image = array();
				$y = 0;
				$cutImgPathArr = array();



				try{
					//切割图片
					for($i=0;$i<$imgCount;$i++){
						if($i == $imgCount-1){
							$target_image= imagecreatetruecolor($imgWidth, ($imgHeight%$imgWidth ? $imgHeight%$imgWidth :$imgHeight));
							imagecopy($target_image, $source_image, 0, 0, 0, $y, $imgWidth, ($imgHeight%$imgWidth ? $imgHeight%$imgWidth :$imgHeight));
						}else{
							$target_image= imagecreatetruecolor($imgWidth, $imgWidth);
							imagecopy($target_image, $source_image, 0, 0, 0, $y, $imgWidth, $imgWidth);
						}
						$newFile_cut = '../upload/' . 'cut_' .  $imgName . $i.'.' . $imgType;
						$cutImgPathArr[$i] = $newFile_cut;
						imagejpeg($target_image,$newFile_cut,100);
						imagedestroy($target_image);
						$y += $imgWidth;
					}
					unlink($filePath);
					imagedestroy($source_image);
				}catch(Exception $e){
					unlink($filePath);
					imagedestroy($source_image);
					$image->deletePics($cutImgPathArr);
					$appLog->warn($e);
					return $string;
				}
				$cid = $this->getUploadDir();
				$newHtml = '';
				foreach($cutImgPathArr as $k => $v){
					$param = array(
						'cid' => $cid ? $cid : 0,
						'img' => '@'.dirname(__FILE__).'/'.$v,
						'inputtitle' => time().$k
					);
					try{
						$res =$this->uploadPicture($param);//将裁剪好的图片上传到图片空间
					}catch(Exception $e){
						//$appLog->warn($e);
						$image->deletePics($cutImgPathArr);
						return $string;
					}
					if($res['error_response']){
						
						$appLog->warn(json_encode($res['error_response']));
						return $string;
					}else{
						$newCutImgPathArr[$k] = $res['picture_upload_response']['picture']['picture_path'];
						$newHtml .= '<img class="cms-animateAreaBg img-lazyload" src="https://img.alicdn.com/imgextra/i3/21451241/TB2ganSiVXXXXbpXpXXXXXXXXXX-21451241.png" data-src="'.$res['picture_upload_response']['picture']['picture_path'].'_640x640q75.jpg_.webp">';
					}
				}

				if(!empty($newHtml)){
					$replaceString = str_replace($imgCode,$newHtml,$string);
				}else{
					$replaceString = $string;
					//$appLog->warn('error');
				}
				$image->deletePics($cutImgPathArr);
				return $replaceString;
			}else{
				unlink($filePath);
				$image->deletePics('not found file');
				return $string;
			}

		}




	}




	/*
	 * 替换收藏模块店铺名称
	 */
	public function replaceShopName($string){
		$nick = $_SESSION['nick'];
		$shopInfo = $this->getShopInfo(array('nick'=>$nick));
		if(!$shopInfo['error_response']){
			$shopName = $shopInfo['shop_get_response']['shop']['title'];
			$logoPath = 'https://img.alicdn.com'.$shopInfo['shop_get_response']['shop']['pic_path'];
			$replaceString = str_replace('shopname_tms',$shopName,$string);
			$replaceString = str_replace('shoplogo_tms',$logoPath,$replaceString);
		}
		return $replaceString ? $replaceString : $string;

	}
	/*
	 * 创建无线专享默认图片目录
	 */
	public function createPicDir(){
		$picParams['cateName'] = '美美搭专用（勿删）';
		$picParams['pid'] = 0;
		$res = $this->getPictureCategory($picParams);
		$cateList = $res['picture_category_get_response']['picture_categories'];
		if(empty($cateList)){
			$createParam['title'] = '美美搭专用（勿删）';
			$createParam['parent_id'] = 0;
			$this->createCategory($createParam);
		}
	}
	/*
	 * 获取无线专享默认图片目录
	 */
	public function getUploadDir(){
		$picParams['cateName'] = '美美搭专用（勿删）';
		$picParams['pid'] = 0;
		$res = $this->getPictureCategory($picParams);
		$cateList = $res['picture_category_get_response']['picture_categories'];
		$catId = $cateList['picture_category'][0]['picture_category_id'];
		return $catId;
	}

	/*
	 * Smarty模板与数据合并生成html代码
	 */
	public function render($moduleName,$moduleData){
		include_once("../Smarty/Smarty.class.php");
		$smarty = new Smarty();
		$smarty->template_dir = '../module/';
		$smarty->compile_dir = '../smarty/template_c';
		$smarty->config_dir  = '../smarty/config';
		$smarty->caching = false; //缓存方式
		$smarty->assign('m',$moduleData); //进行模板变量替换
		$output = $smarty->fetch("$moduleName/m.tpl");
		$dir = '../Smarty/template_c';
		$this->deldir($dir);
		//热区图片切割
		if(stripos($output,'cms-hot-area-content')){
			$output = $this->cutHotareaImg($output);
		}

		//动画模块切割
		if(stripos($output,'cms-animateArea')){
			$output = $this->cutAnimateImg($output);
		}
		//收藏模块替换店铺名称
		if(stripos($output,'cms-collect')){
			$output = $this->replaceShopName($output);
		}
		return $this->replaceString($output);
	}
	/*
	 * 生成页面html代码
	 * params array $pageData
	 * return $module_html
	 */
	public function renderHtml($pageData){
		$html_str = "";
		$style_str = "";
		$moduleArr= array();
		foreach($pageData as $k=>$v)
		{
			$moduleData = $v['data'];
			$moduleData['id'] = $v['id'];
			$moduleName = $v['mid'];
			if(!file_exists('../module/'.$moduleName.'/config.json')){
				$moduleNameArr = explode('_',$moduleName);
				$moduleName = 't1_'.$moduleNameArr[1];
			}
			$html = $this->render($moduleName,$moduleData);
			$html_str .= $html;
			if(!in_array($moduleName,$moduleArr)){
				$moduleArr[] = $moduleName;
				$stylePath = '../module/'.$moduleName.'/m.css';
				$style =$this->getFileContents($stylePath);
				//$style = file_get_contents($stylePath);
				$style_str .= $style;
			}
			
		 //animation css
		  if($moduleName == 'animatearea')
		  {
			  $html_str .= '<link rel="stylesheet" href="assets/animate.css">';
			  
		  }
		}
		unset($moduleArr);
		$html_str = $this->replaceString($html_str);
		//$style_str = $this->replaceString($style_str);
		$module_html = '';
		$module_html .= "<style>";
		$module_html .=  $style_str;
		$module_html .= "</style>";
		$module_html .= $html_str;
		return $module_html;
	}

	/*
	 * 删除文件夹内所有文件
	 */
	public function deldir($dir){
		$dh=opendir($dir);
		while ($file=readdir($dh)) {
			if($file!="." && $file!="..") {
				$fullpath=$dir."/".$file;
				if(!is_dir($fullpath)) {
					unlink($fullpath);
				} else {
					deldir($fullpath);
				}
			}
		}
		closedir($dh);
	}

	/*
	*数组合并、去重
	*/
	public function arrayMerge($arr1,$arr2,$key){
		if(!count($arr1)){
			return $arr2;
		}
		if(!count($arr2)){
			return $arr1;
		}
		foreach($arr1 as $k => $v){
			if(empty($arr2)){
				return $arr1;
			}
			foreach($arr2 as $kk => $vv){
				if($v[$key] == $vv[$key]){
					unset($arr2[$kk]);
				}
			}
		}
		return array_merge($arr1,$arr2);
	}

	/*
	互动register
	*/
	public function activeRegister($params)
	{
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('alibaba.interact.activity.register');
		$tbsb->set('entry_url',$params['entry_url']);
		$tbsb->set('biz_id',$params['biz_id']);
		$tbsb->set('name',$params['name']);
		$tbsb->set('has_valid_time','false');
		$resp = $tbsb->get();
		return $resp ;
	}

	/*
	同步到神笔banner
	*/
	public function pushToShenbi($params)
	{
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('alibaba.interact.activity.apply');
		$tbsb->set('benefit_type','1');
		$tbsb->set('benefit_denomination','10');
		$tbsb->set('banner_url',$params['banner_url']);
		$tbsb->set('activity_biz_id',$params['activity_biz_id']);
		$tbsb->set('biz_type','3');
		$tbsb->set('benefit_amount','100');
		$tbsb->set('benefit_attribute','100');
		$resp = $tbsb->get();
		return $resp ;
	}
	
	/*
	发微淘
	*/
	public function pushFeed($params)
	{
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('taobao.weitao.feed.synchronize');
		$tbsb->set('biz_id',$params['biz_id']);
		$tbsb->set('cover_path',$params['cover_path']);
		$tbsb->set('detail_url',$params['detail_url']);
		$tbsb->set('end_time',$params['end_time']);
		$tbsb->set('start_time',$params['start_time']);
		$tbsb->set('summary',$params['desc']);
		$tbsb->set('title',$params['title']);
		$resp = $tbsb->get();
		return $resp ;
	}

	/*
	 * 设置cookie（流量统计）
	 */
	public function setCookie($ip){
		//$browser =$context->getBrowser();
		//$mixUserNick = $browser->nick;
		$mixUserNick = '';
		if($mixUserNick){
			$mmdid = strtoupper(md5($mixUserNick));
		}else{
			$mmdid = strtoupper(md5(uniqid($ip)));
		}
		setcookie('mmdid', $mmdid, time()+86400000);
		return $mmdid;
	}
	/*
	alibaba.interact.aopdata.register (资源位数据推送接口)
	@desc banner推送到手淘详情页的第三个TAB
	*/
	public function pushDetails3Tab($params)
	{
		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('alibaba.interact.aopdata.register');
		$tbsb->set('param_top_isv_decorate_param',json_encode($params));
		$resp = $tbsb->get();
		return $resp ;
		
	}

	/*
	@desc get dynamic module ids
	$params['html'];
	*/
	public function getDynamicModuleIds($params)
	{
		include_once(dirname(__FILE__).'/simplehtmldom.php');
		$str = str_get_html("'".$params['html']."'");
		//$str = '<body><div><dynamicrender moduleid="1">  			<ul class="itemlist">  				<li class="item" data-itemid="18411539566">  					<a href="#">  						<span class="title">模板测试 韩版2012秋冬新款女装羊羔绒棉服外套加厚棉衣</span>  					</a>  					<div class="price" >123.00</div>  				</li>  				<li class="item" data-itemid="16853305057">  					<a href="#">  						<span class="title">模板测试 韩版2012秋冬新款女装羊羔绒棉服外套加厚棉衣</span>  					</a>  					<div class="price">123.00</div>  				</li>  			</ul>  		</dynamicrender><span>hello world...</span></div></body><body><div><dynamicrender moduleid="5">  			<ul class="itemlist">  				<li class="item" data-itemid="18411539566">  					<a href="#">  						<span class="title">模板测试 韩版2012秋冬新款女装羊羔绒棉服外套加厚棉衣</span>  					</a>  					<div class="price" >123.00</div>  				</li>  				<li class="item" data-itemid="16853305057">  					<a href="#">  						<span class="title">模板测试 韩版2012秋冬新款女装羊羔绒棉服外套加厚棉衣</span>  					</a>  					<div class="price">123.00</div>  				</li>  			</ul>  		</dynamicrender><span>hello world...</span></div></body>';
		$html = str_get_html("'".$str."'");
		$result = array();
		$moduleIds ='';
		foreach($html->find('DynamicRender[moduleid]') as $modules)
		{
			$moduleIds .= $modules->getAttribute('moduleid');
			$moduleIds .= ',';
			
		}
		$result['moduleIds'] = rtrim($moduleIds,',');
		//$result['expireTime'] =  time() + 3600; //1小时过期
		$result['expireTime'] =  time() + 3600; //1小时过期
		return $result;
		
	}
	/*
	@desc 分析html，将动态模块的下次更新时间全部置为活动开始时间
	$pageId
	$html : 页面html
	*/
	public function setNextUpdateTime($pageId,$html)
	{

		include_once(dirname(__FILE__).'/simplehtmldom.php');

		
		$html = str_get_html("'".$html."'");


		$result = array();
		foreach($html->find('DynamicRender[moduleid]') as $module)
		{
			$moduleId = $module->getAttribute('moduleid');
			
			$dynamic = $html->find('DynamicRender[moduleid='.$moduleId.']',0);
			if($dynamic == '')
			{
				$beginTime = 0;
			}
			else
			{
				$begintimeInput = $dynamic->getAttribute('begintime');
				$beginTime = strtotime($begintimeInput); 
				if(empty($begintimeInput)){
					$beginTime = 0;
				}
			}
			$result[$moduleId] = $beginTime;
		}
		$this->setCache('nextUpdateTime'.'_'.$pageId,json_encode($result));

	}
	
	
	/*
	@desc dynamic real time image
	*/
	public function realTimeItemImgUpdate($shopId,$pageId,&$html,&$config,$dynamicModleIds,$ifBackup)
	{
		$ret = 0;
		//TODO next  real time item img update from cache
		$nextRealTimeItemImgUpdate = $this->getCache('nextRealTimeItemImgUpdate_'.$pageId);

		if(time() < $nextRealTimeItemImgUpdate)
		{
			return $ret;
		}
		if($ifBackup)
		{
			$this->getHtmlAndConfigByPageId($pageId,$html,$config,'`backup`');
		}
		else
		{
			$this->getHtmlAndConfigByPageId($pageId,$html,$config,'`h5pages`');
		}




		
		foreach($dynamicModleIds as $moduleId=>$updateTime)
		{

			$dynamic = $html->find('DynamicRender[moduleid='.$moduleId.']',0);
			//获取是否更新realtime 主图标志位

			$realTimeItemImg = $dynamic->getAttribute('realtimeitemimg'); 
			if(!$realTimeItemImg )
			{
				continue;
			}
			$ret = 1;
			foreach($dynamic->find('li[data-itemid]') as $itemId)
			{
				$id = $itemId->getAttribute('data-itemid');

				if($id)
				{

					$params['shopId'] = $shopId;
					$params['item_id'] = $id;
					$params['num_iid'] = $id;
					

					$fetchItem = $this->fetchItem($id);

					$historyImg = $itemId->find('.dynamic-img',0)->getAttribute('data-src');
					preg_match('/^[http|https](.*)(_(\d{3})x(\d{3})q(\d{2}).jpg_.webp)/', $historyImg, $result);
					$imgSize = $result[2];
					
					$itemInfo = $this->fetchItem($id);
					$itemId->find('.dynamic-img',0)->setAttribute('data-src',$itemInfo['img'].$imgSize) ;
					
					
					if($config[$moduleId]['data']['titles'] && is_array($config[$moduleId]['data']['titles']))
					{
						//tab list
						foreach($config[$moduleId]['data']['titles'] as $sk=>$sv)
						{
							if($config[$moduleId]['data']['titles'][$sk]['items']['list'][$id])
							{
							$config[$moduleId]['data']['titles'][$sk]['items']['list'][$id]['img'] = $itemInfo['img'];//替换现价
							}
						
						}
						
					}
					elseif(	$config[$moduleId]['data']['items']['list'] && is_array($config[$moduleId]['data']['items']['list']))
					{
						//common list
					
						$config[$moduleId]['data']['items']['list'][$id]['img'] = $itemInfo['img']; //替换主图到Database
					}

				}
			}
			
		}	
		$nexttime = strtotime( date("Y-m-d H",time()).":00:00" ) +3600 + 60;
		$this->setCache('nextRealTimeItemImgUpdate_'.$pageId,$nexttime);
		return $ret;
	}

	/*
	@desc real time item price
	*/
	public function realTimeItemPriceUpate($shopId,$pageId,&$html,&$config,$dynamicModleIds,$ifBackup)
	{
		$ret = 0;
		foreach($dynamicModleIds as $moduleId=>$updateTime)
		{


			if(time() < $updateTime)
			{
				continue;
			}
			$ret = 1;
			if($ifBackup)
			{
				$this->getHtmlAndConfigByPageId($pageId,$html,$config,'`backup`');
			}
			else
			{
				$this->getHtmlAndConfigByPageId($pageId,$html,$config,'`h5pages`');
			}
			$dynamic = $html->find('DynamicRender[moduleid='.$moduleId.']',0);
			$beginTime = strtotime($dynamic->getAttribute('begintime')); //图片缓存开始时间
			$endTime = strtotime($dynamic->getAttribute('endtime'));//图片缓存结束时间

			foreach($dynamic->find('li[data-itemid]') as $itemId)
			{
				$id = $itemId->getAttribute('data-itemid');

				if($id)
				{
					// api get price
					$params['shopId'] = $shopId;
					$params['item_id'] = $id;
					$params['num_iid'] = $id;
					

					$fetchItem = $this->fetchItem($id);
					$discountPrice = $fetchItem['discountprice'];
					$price = $fetchItem['price'];

					if($discountPrice && $discountPrice!=$price)
					{
						if($itemId->find('.pricenow',0)){
							$itemId->find('.pricenow',0)->innertext= '<span>&yen;</span>'.$discountPrice; //替换现价	
						}

						if($itemId->find('.priceold',0)){
							$itemId->find('.priceold',0)->innertext= '<span>&yen;:</span>'.$price;  //替换原价
						}
						
						$priceTemp = explode('.',$discountPrice); 

						if($itemId->find('.price',0)){
							$itemId->find('.price',0)->innertext= '<span class="yen">&yen;</span>'.$priceTemp[0]; //替换现价
						}
						
						if($config[$moduleId]['data']['titles'] && is_array($config[$moduleId]['data']['titles']))
						{
							//tab list
							foreach($config[$moduleId]['data']['titles'] as $sk=>$sv)
							{
								if($config[$moduleId]['data']['titles'][$sk]['items']['list'][$id])
								{
								$config[$moduleId]['data']['titles'][$sk]['items']['list'][$id]['price'] = $discountPrice;//替换现价
								$config[$moduleId]['data']['titles'][$sk]['items']['list'][$id]['oldPrice'] = $price;//替换现价
								}
							}
							
						}
						elseif(	$config[$moduleId]['data']['items']['list'] && is_array($config[$moduleId]['data']['items']['list']))
						{
							//common list
							$config[$moduleId]['data']['items']['list'][$id]['price'] = $discountPrice;//替换现价
							$config[$moduleId]['data']['items']['list'][$id]['oldPrice'] = $price;//替换现价
						}	


					}
					elseif($price && $discountPrice == $price)
					{
						if($itemId->find('.pricenow',0)){
							$itemId->find('.pricenow',0)->innertext= '<span>&yen;</span>'.$price; //替换现价
						}
						
						if($itemId->find('.priceold',0)){
							$itemId->find('.priceold',0)->innertext= ''; //替换原价
						}

						$priceTemp = explode('.',$price);

						if($itemId->find('.price',0)){
							$itemId->find('.price',0)->innertext= '<span class="yen">&yen;</span>'.$priceTemp[0]; //替换现价
						}
						
						if($config[$moduleId]['data']['titles'] && is_array($config[$moduleId]['data']['titles']))
						{
							//tab list
							foreach($config[$moduleId]['data']['titles'] as $sk=>$sv)
							{
								if($config[$moduleId]['data']['titles'][$sk]['items']['list'][$id])
								{
									$config[$moduleId]['data']['titles'][$sk]['items']['list'][$id]['price'] = $price;//替换现价
								}
							
							}
							
						}
						elseif(	$config[$moduleId]['data']['items']['list'] && is_array($config[$moduleId]['data']['items']['list']))
						{
							//common list
							$config[$moduleId]['data']['items']['list'][$id]['price'] = $price;//替换现价 
						}

					}


				}
			}
			//设置单模块下次更新时间

			$nexttime = strtotime( date("Y-m-d H",time()).":00:00" ) +3600 + 60;

			$dynamicModleIds[$moduleId] = $nexttime;

			if($endTime != '' && ($endTime>time() && $endTime < $nexttime)) //结束时间在一个小时之内
			{
				$dynamicModleIds[$moduleId] = $endTime;
			}

		}

		//update 动态模块的cache
		$this->setCache('nextUpdateTime'.'_'.$pageId,json_encode($dynamicModleIds));
		return $ret;

	}
	/*
	取得html 和 config 
	*/
	public function getHtmlAndConfigByPageId($pageId,&$html,&$config,$table='`h5pages`')
	{
		include_once(dirname(__FILE__).'/simplehtmldom.php');

		if($html && $config)
		{
			return;
		}
		//查DB

		$pageData = $this->getDynamicModulesConfig($pageId,$table);//get config from database
		$config = $this->rebuildConfigWithKey($pageData['CONFIG']);//rebuild module key	
		$html = urldecode($pageData['HTML']);
		$html = str_get_html($html);
 
	}
	/*
	定时发布
	0:表示主表h5page ,1:表示备份表backup
	*/
	public function autoPublish($pageId,&$html,&$config)
	{

		$autoPublishTime = $this->getCache('autoupdate_page_'.$pageId);

		if(empty($autoPublishTime))
		{
			return 0;
		}



		$autoPublish = $autoPublishTime < time();

		if($autoPublish) //需要发布了
		{
			$this->getHtmlAndConfigByPageId($pageId,$html,$config);
			$this->setCache('cache_html_'.$pageId,$html->outertext);

			$html_str = $html->outertext;

			//setNextUpdateTime 换价格
		 	$this->setNextUpdateTime($pageId,$html_str);

		 	//页面级realitemimg cache 换图
		 	$this->setCache('nextRealTimeItemImgUpdate_'.$pageId,time());

			$this->delCache('autoupdate_page_'.$pageId);

			return 0;
		}
		else
		{
			return 1;
		}
	}

	public function dynamicQueueFromCacheAsync($shopId,$pageId){

		$hosts = NULL;
		$connect = NULL;
		$url = NULL;

		if(ENV=='DEV'){
			$hosts = array("127.0.0.1");
			$connect = "tcp://127.0.0.1:80";
			$url = '/mmd/tms/interface/dynamicupdate.php';
		}else{
			$hosts = array("10.132.167.183");
			$connect = "10.132.167.183:5000";
			$url = '/tms/interface/dynamicupdate.php';
		}

		
		$timeout = 1;
		$status = array();
		$sockets = array();
		/* Initiate connections to all the hosts simultaneously */
		foreach ($hosts as $id => $host) {
		    $s = stream_socket_client($connect, $errno, $errstr, $timeout, 
		        STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);
		    if ($s) {
		        $sockets[$id] = $s;
		        $status[$id] = "in progress";
		    } else {
		        $status[$id] = "failed, $errno $errstr";
		        $appLog->warn("failed, $errno $errstr");
		    }
		}
		
			
	    $read = $write = $sockets;
	    $n = stream_select($read, $write, $e = null, $timeout);

	    if ($n > 0) {

	        foreach ($read as $r) {
	            $id = array_search($r, $sockets);
	            $data = fread($r, 8192);
	            if (strlen($data) == 0) {
	                if ($status[$id] == "in progress") {
	                    $status[$id] = "failed to connect";
	                }
	                fclose($r);
	                unset($sockets[$id]);
	            } else {
	                $status[$id] .= $data;
	            }
	        }
	        foreach ($write as $w) {
	            $id = array_search($w, $sockets);
	            fwrite($w, "GET ".$url."?shopId=".$shopId."&pageId=".$pageId."\r\nHTTP/1.1\r\n"."Connection: close\r\n");
	            $status[$id] = "waiting for response<BR>";
	        }
	    }		

		
	}
	/*
	@desc queue for dynamic
	$pageId
	*/
	public function dynamicQueueFromCache($shopId,$pageId)
	{
		//避免多线程同时更新，导致错误HTML覆盖到数据库
		$updating = $this->getCache('dynamic_module_current_updating_'.$pageId);
		if($updating == true){
			return;
		}

		$this->setCache('dynamic_module_current_updating_'.$pageId,true,100);


		$html = '';
		$config = '';
		//是否定时发布页面
		$ifBackup = $this->autoPublish($pageId,$html,$config);

		//老数据校验
		/*
		$dynamicModules = $this->getCache('dynamic_modules_'.$pageId);	
		if($dynamicModules) 
		{
			$html = $this->getCache('cache_html_'.$pageId);
			$this->setNextUpdateTime($pageId,$html);
			$this->delCache('dynamic_modules_'.$pageId);	
		}
		*/
		//获取下一次更新时间
		$nextUpdateTime = $this->getCache('nextUpdateTime'.'_'.$pageId);
		if(empty($nextUpdateTime))
		{
			$this->setCache('dynamic_module_current_updating_'.$pageId,false);
			return;
		}


		include_once(dirname(__FILE__).'/simplehtmldom.php');
		$dynamicModleIds = json_decode($nextUpdateTime,true);

		if(empty($dynamicModleIds))
		{
			$this->setCache('dynamic_module_current_updating_'.$pageId,false);
			return;
		}

		//realtime 图

		$realTimeImageResult = $this->realTimeItemImgUpdate($shopId,$pageId,$html,$config,$dynamicModleIds,$ifBackup);
		//realtime 价格
		$realtimePriceResult = $this->realTimeItemPriceUpate($shopId,$pageId,$html,$config,$dynamicModleIds,$ifBackup);

		

		if($realTimeImageResult || $realtimePriceResult )
		{
			//update database
			$this->setCache('cache_html_'.$pageId,$html->outertext);

			$params['pageId'] = $pageId;
			$params['config'] = $this->removeConfigKey($config);
			$params['html'] = $html->outertext;
			if($ifBackup)
			{

				$this->updateDynamicModulesConfig($params,'backup');
			}
			else
			{
				$this->updateDynamicModulesConfig($params);
			}
		}

		$this->setCache('dynamic_module_current_updating_'.$pageId,false);


	}


	
	/*
	@desc get pageconfig 
	*/
	public function getDynamicModulesConfig($pageId,$table='`h5pages`')
	{
	
	
		$pdo = new Dao_Pdo();
		$sql = "SELECT * FROM  {$table} where PAGE_ID = {$pageId} and STATUS = 'active'";
		$result = $pdo->get_one($sql);
		return $result;
		
	}
	
	/*
	@desc rebuild config with key
	$config : config form database;
	*/
	public function rebuildConfigWithKey($config)
	{
		$configKey = array();
		$config = json_decode(urldecode($config),true);
		foreach($config as $k=>$v)
		{
			$configKey[$v['id']] = $v;
			if($v['data']['items']['list'] && is_array($v['data']['items']['list']))
			{
				//common list
				foreach($v['data']['items']['list'] as $sk=>$sv)
				{
					
					$configKey[$v['id']]['data']['items']['list'][$sv['id']] = $sv;
					unset($configKey[$v['id']]['data']['items']['list'][$sk]);
					
				}
				
			}
			elseif($v['data']['titles'] && is_array($v['data']['titles']))
			{
				//tab list
			
				foreach($v['data']['titles'] as $sk=>$sv)
				{
					
					foreach($sv['items']['list'] as $tk=>$tv)
					{
						$configKey[$v['id']]['data']['titles'][$sk]['items']['list'][$tv['id']] = $tv;
						unset($configKey[$v['id']]['data']['titles'][$sk]['items']['list'][$tk]);
					}
					
				}
			}

		}
		return $configKey;
		
	}
	/*
	@desc rebuild remove key
	*/
	public function removeConfigKey($config)
	{
		$removeConfig = array();
		$config = array_values($config);

		foreach($config as $k=>$v)
		{
			//common list
			if($v['data']['items']['list'] && is_array($v['data']['items']['list']))
			{	

				$config[$k]['data']['items']['list'] = array_values($v['data']['items']['list']);
			}
			elseif($v['data']['titles'] && is_array($v['data']['titles']))
			{
				//tab list
			
				foreach($v['data']['titles'] as $sk=>$sv)
				{
					$config[$k]['data']['titles'][$sk]['items']['list'] = array_values($sv['items']['list']);

				}
			}

		}
		return $config;
	}
	
	
	/*
	@desc update database for dynamic modules
	$params['config']
	$params['pageId']
	*/
	public function updateDynamicModulesConfig($params,$table='h5pages')
	{
		$pdo = new Dao_Pdo();
		$page['CONFIG'] = urlencode(json_encode($params['config']));
		$page['HTML'] = urlencode($params['html']);
		$page['UPDATE_TIME'] = date('Y-m-d H:i:s');
	
		$condition = "PAGE_ID = '".$params['pageId']."'";
		try{
			$activeDao = $pdo->update($table,$page,$condition);
			return true;
		}catch(Exception $e){
			echo $e->getMessage();
			return false;
		}

	}

	public function test(){

		$tbsb = new Services_Tbsb();
		$tbsb->setSession($_SESSION['access_token']);
		$tbsb->query('tmall.traderate.itemtags.get');
		$tbsb->set('item_id','41177291226');
		$resp = $tbsb->get();
		return $resp ;
	}
	
}
?>